package com.xishu.shard;

import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

import java.util.Collection;

public class DatabaseSharding implements PreciseShardingAlgorithm<Long> {

    /**
     * 代表实现分片，不走配置文件，方便控制
     *
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        ShardUtil shardUtil = ShardUtil.getInstance();

        //有商铺ID的
        if (shardingValue.getValue() != null) {
            long dbSerial = shardingValue.getValue() % shardUtil.getDbMap().size();
            return shardUtil.getDbMap().get(dbSerial);
        } else {
            //没有商铺ID的不分库
            return shardUtil.getDbMap().get(0);
        }
    }
}
